package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import dao.DinDao;
import model.User;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    /**
     * 向用户登录页面跳转
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(){
        return  "login.jsp";
    }

    /**
     * 用户登录
     * @param user
     * @param model
     * @param session
     * @return
     */
    @Autowired
    DinDao din;
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(User user, Model model, HttpSession session){  	
        //获取用户名和密码
        String username=user.getUsername();
        String password=user.getPassword();
        System.out.println("输入的是: "+username+"     "+password);
        
        //获得数据库的内容
        List<User> list = din.selectUser();
        for(User l:list) {
            String DBname = l.getUsername();
            String DBpassword = l.getPassword();
        	System.out.println("数据库中的账号: "+l.getUsername());
        	System.out.println("数据库中的密码: "+l.getPassword());
        	 //些处横板从数据库中获取对用户名和密码后进行判断
            if(username!=null&&username.equals(DBname)&&password!=null&&password.equals(DBpassword)){               
                //重定向到主页面的跳转方法
            	session.setAttribute("USER_SESSION",user);
            	session.setAttribute("test", "测试redirect");
            	model.addAttribute("manager", DBname);
            	System.out.println("账号密码正确，执行跳转！");
            	//测试得出结论：redirect时候 session不会消失 ,但model传值会消失
                return "forward:selectAll";          	
            }
        }     
        model.addAttribute("msg","用户名或密码错误，请重新登录！");
        return "login.jsp";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
    	        session.invalidate();
                //重定向到登录页面的跳转方法
    	        return "redirect:NewFile.jsp";
    }
    
    @RequestMapping("/insertUser")
    public String insertUser(User u,Model model,HttpServletRequest request) {
    	int rows = din.insertUser(u);
    	if(rows > 0) {
    		String name = u.getUsername();
    		System.out.println("用户注册成功！");
    		model.addAttribute("vic","用户: "+ name+"注册成功！");
    	}
       return "login.jsp";
    }
}